package com.dearbinge.data.service.impl.cart;

import com.baomidou.mybatisplus.plugins.Page;
import com.dearbinge.data.api.cart.CartService;
import com.dearbinge.data.dao.CommodityMessageMapper;
import com.dearbinge.data.dao.ShopManageMapper;
import com.dearbinge.data.dao.cart.CartMapper;
import com.dearbinge.data.dao.commodityspec.CommoditySpecMapper;
import com.dearbinge.data.pojo.cart.Cart;
import com.dearbinge.data.pojo.cart.vo.CartVO;
import com.dearbinge.data.pojo.commodity.CommodityMessage;
import com.dearbinge.data.pojo.commodityspec.CommoditySpec;
import com.dearbinge.data.pojo.shopManage.ShopManage;
import com.dearbinge.utils.PageUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 说明
 *
 * @author cl
 * @date 2019/1/10
 */
@Service("cartService")
public class CartServicelmpl implements CartService {

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private ShopManageMapper shopManageMapper;

    @Autowired
    private CommoditySpecMapper commoditySpecMapper;

    @Autowired
    private CommodityMessageMapper commodityMessageMapper;

    /**
     * 增加指定商品库存
     *
     * @param commodityId 商品id
     * @return 结果
     */
    @Override
    public Integer getCommodityStock(String commodityId) {
        Integer integer = cartMapper.getCommodityStock(commodityId);

        return integer;
    }

    /**
     * 查询商品是否存在用户购物车
     *
     * @param cart 商品
     * @return 结果
     */
    @Override
    public CartVO getCommodityInCart(Cart cart) {
        CartVO cartVO = cartMapper.getCommodityInCart(cart);
        return cartVO;
    }


    /**
     * 增加购物车
     *
     * @param cart 购物车
     * @return 结果
     */
    @Override
    public Integer insertCart(Cart cart) {
        Integer integer = cartMapper.insertCart(cart);
        return integer;
    }

    /**
     * 修改购物车
     *
     * @param cart 购物车
     * @return 结果
     */
    @Override
    public Integer updateCart(Cart cart) {
        return cartMapper.updateCart(cart);
    }

    /**
     * 删除
     *
     * @param id id
     * @return 结果
     */
    @Override
    public Integer deleteCart(Integer id) {
        return cartMapper.deleteCart(id);
    }

    /**
     * 清空指定用户的失效商品购物车
     *
     * @param userId userId
     * @return 结果
     */
    @Override
    public Integer deleteUserFailureCart(String userId) {
        Integer dataCode = 0;
        //根据用户id查询指定用户的购物车
        List<CartVO> list = cartMapper.listCartByUserId(null, userId);
        for (int index = 0; index < list.size(); index++) {
            //购物车id
            Integer cardId = list.get(index).getId();
            //商品id
            Integer commodityId = Integer.valueOf(list.get(index).getCommodityId());
            //根据商品id查询商品信息（下架 删除的也返回）
            CommodityMessage commodityMessage = commodityMessageMapper.getCommodityById(commodityId);
            if (commodityMessage.getDeleted() == true || commodityMessage.getCommodityStatus() == false) {
                dataCode = cartMapper.deleteCart(cardId);
            }
        }
        return dataCode;
    }

    public Page listCartByUserId(String userId, Integer current, Integer size) {

        current = PageUtils.getDefaultValues(current, 1);
        size = PageUtils.getDefaultValues(size, 10);
        Page<Map<String, Object>> page = new Page<Map<String, Object>>(current, size);
        List<Map<String, Object>> lists = new ArrayList<Map<String, Object>>();
        Map failurelistMap = new HashMap();
        List failurelist = new ArrayList();
        //获取用户加入购物车的店铺
        List<Map<String, Object>> cartListVOS = cartMapper.getCommodityBeShop(userId, page);

        for (int index = 0; index < cartListVOS.size(); index++) {
            Map<String, Object> map = new HashMap<String, Object>();
            String shopId = cartListVOS.get(index).get("shopId").toString();
            //根据店铺id获取店铺信息
            ShopManage shopMessage = shopManageMapper.getByshopCode(null, shopId);
            if (shopMessage == null) {
                continue;
            }
            //储存店铺名称
            cartListVOS.get(index).put("shopName", shopMessage.getShopName());
            //储存店铺名称
            cartListVOS.get(index).put("shoplogo", shopMessage.getShopLOG());
            //获取用户指定店铺的购物车信息
            List<CartVO> list = cartMapper.listCartByUserId(shopId, userId);
            for (int i = 0; i < list.size(); i++) {
                //店铺名称
                list.get(i).setShopName(shopMessage.getShopName());
                //规格id
                Integer commoditySpecId = Integer.valueOf(list.get(i).getCommoditySpecId());
                //根据购物车规格id查询规格名称
                CommoditySpec commoditySpec = commoditySpecMapper.selectById(commoditySpecId);
                //商品id
                Integer commodityId = Integer.valueOf(list.get(i).getCommodityId());
                //根据商品id查询商品信息（下架 删除的也返回）
                CommodityMessage commodityMessage = commodityMessageMapper.getCommodityById(commodityId);
                //商品是否失效 （下架、删除）
                if (commodityMessage.getDeleted() == true || commodityMessage.getCommodityStatus() == false) {
                    list.get(i).setIsFailure(1);
                } else {
                    list.get(i).setIsFailure(0);
                }
                //商品名称
//                if (commodityMessage != null) {
                    list.get(i).setCommodityName(commodityMessage.getCommodityName()!= null?commodityMessage.getCommodityName():"");
//                }
                //商品图片
//                if (commodityMessage != null) {
                    list.get(i).setImgUrl(commodityMessage.getImgUrl()!=null?commodityMessage.getImgUrl():"");
//                }
                //商品运费
//                if (commodityMessage != null) {
                    list.get(i).setFreight(String.valueOf(commodityMessage.getFreight())!=null?String.valueOf(commodityMessage.getFreight()):"");
//                }
                //商品规格名称
//                if (commoditySpec.getSpecificationDesc() != null) {
                    list.get(i).setCommoditySpecName(commoditySpec.getSpecificationDesc()!= null?commoditySpec.getSpecificationDesc():"");
//                }
                //商品零售价
//                if (commodityMessage != null) {
//                    list.get(i).setRetailPrice(commodityMessage.getRetailPrice()!= null? commodityMessage.getRetailPrice():new BigDecimal("0"));
//                }
                if (list.get(i).getIsFailure().equals(1)) {
                    failurelist.add(list.get(i));
                }
            }
            //商品list失效的商品
            for(int j=0;j<list.size();j++){
                if (list.get(j).getIsFailure().equals(1)){
                    list.remove(j);
                }
            }
            //这里解决无商品 显示店铺问题 即存在商品才返回
            if (list.size() > 0 ) {
                map.put("commodity", list);
                map.put("shop", cartListVOS.get(index));
                lists.add(map);
            }
        }
        List ll = new ArrayList();
        //失效商品
        failurelistMap.put("failurelist", failurelist);
        failurelistMap.put("valid", lists);
        ll.add(failurelistMap);
        page.setTotal(cartListVOS.size());
        page.setRecords(ll);
        return page;
    }
}
